package com.example.androidcomplete0102.ch19;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

import com.example.androidcomplete0102.R;

public class BackWork2 extends Activity {
	TextView mResult;
	AccumThread mThread;
	ProgressDialog mProgress;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mResult = (TextView)findViewById(R.id.ch19_result);
	}
	
	public void mOnClick(View v){
		int start = 0, end = 100;
		
		mProgress = new ProgressDialog(v.getContext());
		mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgress.setTitle("Calculating");
		mProgress.setMessage("Wait..");
		mProgress.setButton("Cancle", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				mThread.mQuit = true;
				mProgress.dismiss();
			}
		});
		mProgress.show();
		
		mThread = new AccumThread(start, end, mAfterAccum);
		mThread.start();
		
	}
	
	class AccumThread extends Thread{
		int mStart, mEnd;
		int mResult;
		Handler mAfter;
		boolean mQuit;
		
		public AccumThread(int start, int end, Handler after) {
			mStart = start;
			mEnd = end;
			mQuit = false;
			mAfter = after;
		}
		
		public void run(){
			mResult = 0;
			for(int i = mStart; i<=mEnd; i++){
				mResult += i;
				try {
					Thread.sleep(20);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				if(mQuit){
					return;
				}
			}
			mAfter.sendEmptyMessage(0);
		}
	}
	
	Handler mAfterAccum = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			mProgress.dismiss();
			if(mThread.mQuit == false){
				mResult.setText(""+mThread.mResult);
			}
		}
		
	};
}
